package com.ruoyi.web.controller.circle;

import java.util.List;
import java.util.UUID;

import com.ruoyi.circle.domain.CircleTagsRel;
import com.ruoyi.common.constant.Constants;
import com.ruoyi.common.core.domain.entity.SysRole;
import com.ruoyi.common.core.domain.model.LoginUser;
import com.ruoyi.level.dao.IPointsLevelRuleDao;
import com.ruoyi.tag.domain.PostTagsRel;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.enums.BusinessType;
import com.ruoyi.circle.domain.CircleBasicInfo;
import com.ruoyi.circle.service.ICircleBasicInfoService;
import com.ruoyi.common.utils.poi.ExcelUtil;
import com.ruoyi.common.core.page.TableDataInfo;
import io.swagger.v3.oas.annotations.tags.Tag;
import io.swagger.v3.oas.annotations.Operation;

/**
 * 圈子基础信息Controller
 *
 * @author 区嘉盛
 * @date 2025-06-09
 */
@RestController
@RequestMapping("/circle/circle")
@Tag(name = "【圈子基础信息】管理")
public class CircleBasicInfoController extends BaseController {
    @Autowired
    private ICircleBasicInfoService circleBasicInfoService;

    @Autowired
    private IPointsLevelRuleDao pointsLevelRuleDao;

    /**
     * 查询圈子基础信息列表
     */
    @Operation(summary = "查询圈子基础信息列表")
    @GetMapping("/list")
    public TableDataInfo list(CircleBasicInfo circleBasicInfo) {
        startPage();
        List<CircleBasicInfo> list = circleBasicInfoService.selectCircleBasicInfoList(circleBasicInfo);
        return getDataTable(list);
    }

    /**
     * 获取所有圈子
     */
    @Operation(summary = "获取所有圈子")
    @GetMapping("/all")
    public TableDataInfo getAllCircle() {
        List<CircleBasicInfo> list = circleBasicInfoService.getAllCircle();
        return getDataTable(list);
    }

    /**
     * 查询圈子
     */
    @Operation(summary = "查询圈子")
    @GetMapping("/query/{circleName}")
    public TableDataInfo queryCircleByCircleName(@PathVariable String circleName) {
        List<CircleBasicInfo> list = circleBasicInfoService.queryCircleByCircleName(circleName);
        return getDataTable(list);
    }

    /**
     * 导出圈子基础信息列表
     */
    @Operation(summary = "导出圈子基础信息列表")
    @PreAuthorize("@ss.hasPermi('circle:circle:export')")
    @Log(title = "圈子基础信息", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    public void export(HttpServletResponse response, CircleBasicInfo circleBasicInfo) {
        List<CircleBasicInfo> list = circleBasicInfoService.selectCircleBasicInfoList(circleBasicInfo);
        ExcelUtil<CircleBasicInfo> util = new ExcelUtil<CircleBasicInfo>(CircleBasicInfo.class);
        util.exportExcel(response, list, "圈子基础信息数据");
    }

    /**
     * 获取圈子基础信息详细信息
     */
    @Operation(summary = "获取圈子基础信息详细信息")
    @GetMapping(value = "/{id}")
    public AjaxResult getInfo(@PathVariable("id") Long id) {
        return success(circleBasicInfoService.selectCircleBasicInfoById(id));
    }

    /**
     * 获取八个热门圈子基础信息详细信息
     */
    @Operation(summary = "获取圈子基础信息详细信息")
    @GetMapping("/hot")
    public AjaxResult getHotCircle() {
        List<CircleBasicInfo> circleList =  circleBasicInfoService.getHotCircle();
        return success(circleList);
    }

    /**
     * 新增圈子基础信息
     */
    @Operation(summary = "新增圈子基础信息")
    @Log(title = "圈子基础信息", businessType = BusinessType.INSERT)
    @PostMapping
    public AjaxResult add(@RequestBody CircleBasicInfo circleBasicInfo) {
        circleBasicInfo.setCreateUserId(getUserId());
        circleBasicInfo.setCreatedBy(getUsername());
        circleBasicInfo.setCircleCode(UUID.randomUUID().toString().replace("-", ""));
        LoginUser loginUser = getLoginUser();
        if (loginUser != null && loginUser.getUser() != null) {
            List<SysRole> roles = loginUser.getUser().getRoles();
            if (roles != null && !roles.isEmpty()) {
                for (SysRole role : roles) {
                    if (Constants.SUPER_ADMIN.equals(role.getRoleKey())) {
                        circleBasicInfo.setApprovalStatus(1L);
                        break;
                    }
                }
            }
        }
        return toAjax(circleBasicInfoService.insertCircleBasicInfo(circleBasicInfo));
    }

    /**
     * 修改圈子基础信息
     */
    @Operation(summary = "修改圈子基础信息")
    @Log(title = "圈子基础信息", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@RequestBody CircleBasicInfo circleBasicInfo) {
        circleBasicInfo.setUpdatedBy(getUsername());
        return toAjax(circleBasicInfoService.updateCircleBasicInfo(circleBasicInfo));
    }

    /**
     * 删除圈子基础信息
     */
    @Operation(summary = "删除圈子基础信息")
    @Log(title = "圈子基础信息", businessType = BusinessType.DELETE)
    @DeleteMapping("/{ids}")
    public AjaxResult remove(@PathVariable(name = "ids") Long[] ids) {
        return toAjax(circleBasicInfoService.deleteCircleBasicInfoByIds(ids));
    }

    /**
     * 普通用户申请新建圈子
     */
    @Operation(summary = "普通用户申请新建圈子")
    @Log(title = "申请新建圈子", businessType = BusinessType.INSERT)
    @PostMapping("/apply")
    public AjaxResult applyCircle(@RequestBody CircleBasicInfo circleBasicInfo) {
        circleBasicInfo.setCreateUserId(getUserId());
        circleBasicInfo.setCreatedBy(getUsername());
        circleBasicInfo.setCircleCode(UUID.randomUUID().toString().replace("-", ""));
        int rows = circleBasicInfoService.applyCircle(circleBasicInfo);
        if (rows > 0) {
            return AjaxResult.success("新增成功", circleBasicInfo.getId()); // 返回新增标签的ID
        } else {
            return AjaxResult.error("新增失败");
        }
    }

    /**
     * 管理员审批圈子申请
     */
    @Operation(summary = "管理员审批圈子申请")
    @PreAuthorize("@ss.hasRole('admin')")
    @Log(title = "审批圈子申请", businessType = BusinessType.UPDATE)
    @PutMapping("/approve/{id}/{status}")
    public AjaxResult approveCircle(@PathVariable("id") Long id, @PathVariable("status") Long status) {
        if (status != 1L && status != 2L) {
            return error("审批状态参数错误，只能设置为1(已通过)或2(已拒绝)");
        }
        return toAjax(circleBasicInfoService.approveCircle(id, status, getUsername()));
    }

    /**
     * 获取所有等级规则体系名称
     */
    @Operation(summary = "获取所有等级规则系统名称")
    @GetMapping("/levelSystemNames")
    public AjaxResult getLevelSystemNames() {
        List<String> systemNames = pointsLevelRuleDao.selectAllSystemNames();
        return success(systemNames);
    }

    /**
     * 新增圈子与标签中间表
     */
    @Operation(summary = "新增圈子与标签中间表")
    @Log(title = "圈子与标签中间表", businessType = BusinessType.INSERT)
    @PostMapping("/ctr")
    public AjaxResult insertCircleTagsRel(@RequestBody CircleTagsRel circleTagsRel)
    {
        return success(circleBasicInfoService.insertCircleTagsRel(circleTagsRel));
    }

    /**
     * 批量新增圈子与标签中间表
     */
    @Operation(summary = "批量新增圈子与标签中间表")
    @Log(title = "圈子与标签中间表", businessType = BusinessType.INSERT)
    @PostMapping("/ctrs")
    public AjaxResult insertBatchCircleTagsRel(@RequestBody List<CircleTagsRel> circleTagsRelList)
    {
        return success(circleBasicInfoService.insertBatchCircleTagsRel(circleTagsRelList));
    }

    /**
     * 获取我加入的圈子
     */
    @Operation(summary = "获取我加入的圈子")
    @GetMapping("/joined/{userId}")
    public AjaxResult getJoinedCircle(@PathVariable Long userId)
    {
        List<CircleBasicInfo> circleList =  circleBasicInfoService.getJoinedCircle(userId);
        return success(circleList);
    }

    /**
     * 获取我创建的圈子
     */
    @Operation(summary = "获取我创建的圈子")
    @GetMapping("/created/{userId}")
    public AjaxResult getCircleCreatedByMe(@PathVariable Long userId)
    {
        List<CircleBasicInfo> circleList =  circleBasicInfoService.getCircleCreatedByMe(userId);
        return success(circleList);
    }

    /**
     * 获取我正在被审核的圈子
     */
    @Operation(summary = "获取我正在被审核的圈子")
    @GetMapping("/approval/{userId}")
    public AjaxResult getMyApprovalCircle(@PathVariable Long userId)
    {
        List<CircleBasicInfo> circleList =  circleBasicInfoService.getMyApprovalCircle(userId);
        return success(circleList);
    }

    /**
     * 根据标签id获取圈子
     */
    @Operation(summary = "根据标签id获取圈子")
    @GetMapping("/tag/{tagId}")
    public AjaxResult getCircleByTagId(@PathVariable Long tagId)
    {
        List<CircleBasicInfo> circleList =  circleBasicInfoService.getCircleByTagId(tagId);
        return success(circleList);
    }

    /**
     * 获取圈子当天的热搜推送内容与题目推送内容
     */
    @GetMapping("/hotSearchContent/{circleId}")
    public AjaxResult getLatestHotSearchContent(@PathVariable("circleId") Long circleId) {
        return success(circleBasicInfoService.getLatestCircleHotSearchContent(circleId));
    }

    /**
     * 获取圈子全部的热搜推送内容与题目推送内容
     */
    @GetMapping("/allHotSearchContent/{circleId}")
    public AjaxResult getAllHotSearchContent(@PathVariable("circleId") Long circleId) {
        return success(circleBasicInfoService.getAllCircleHotSearchContent(circleId));
    }
}
